package practise.hibernate.dao.impl;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import practise.hibernate.dao.MoiveSiteDao;
import practise.hibernate.persistence.MoiveRecord;
import practise.hibernate.persistence.MoiveSite;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Service("moiveSiteDao")
@Repository
@Transactional
public class MoiveSiteDaoImpl implements MoiveSiteDao {
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional(readOnly = true)
    public List<MoiveSite> findAllMoiveesites() {

        final Query query = entityManager.createQuery("select distinct t from moivesite t");
        return query.getResultList();
    }

    @Override
    @Transactional(readOnly = true)
    public List<MoiveSite> findBySitenumber(Integer sitenumber) {
        final Query query = entityManager.createQuery("select distinct t from moivesite t where t.sitenumber = :sitenumber");
        query.setParameter("sitenumber", sitenumber);
        return query.getResultList();
    }

    @Override
    @Transactional(readOnly = false)
    public void deleteMoive(int id) {
        entityManager.remove(entityManager.find(MoiveSite.class, id));
    }

    @Override
    @Transactional
    public MoiveSite merge(MoiveSite moiveSite) {
        return entityManager.merge(moiveSite);
    }
}
